define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/op/models'),
        user_models = require('js/apps/console/models'),
        utils = require('js/utils/tools'),
        tz = require('js/utils/tz'),
        app = Backbone.history;
    require('datetimepicker');
    require('multiselect');
    require('magnific');

    var RechargeListView = Backbone.View.extend({
        events: {
            'click #search': 'doSearch',
            'click #export': 'exportData',
            'click #releaseBtn': 'doRelease'
        },

        initialize: function (options) {
            this.options = options;
            this.collection = new models.RechargeCollection();
            this.collection.bind('change remove reset', this.renderWithData, this);
            this.user_collection = new user_models.UserCollection();
            this.rechargeStatus = new models.RechargeStatus();
            this.rechargeStatus.bind('change remove reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        exportData: function () {
            notify.warning('警告', '导出中，请等待');
            utils.exportData(this.collection.url, this._getSearchOption());
        },
        _getSearchOption: function () {
            var options = {};
            var searched = utils.getAllInput('#sidebar_right');
            _.each(['status', 'recharge_type'], function (k) {
                if (searched[k] != -1) options[k] = searched[k];
            })
            if (searched.user_id) {
              options.user_id = searched.user_id;
            }
            if (searched.created_at) {
                options.created_at = searched.created_at;
            }
            utils.saveSearched('op/recharge', searched);
            return options;
        },
        doSearch: function () {
            var options = this._getSearchOption();
            options.$page = 1;
            options.$size = 300;
            options._ = new Date().getTime();
            app.navigate(utils.composeQueryString('#op/recharge/', options), {
                trigger: true
            });
        },
        doRelease: function () {
            notify.warning('警告', '设置中，请等待...');
            if ($('#releaseBtn').val() == '开启') {
                var on = 1;
            } else {
                var on = 0;
            }
            $.post('/admin/recharge/set/'+on+'/').done(function (resp) {
                var data = resp.data;
                if (on == 1) { 
                    $('#releaseBtn').val('关闭');
                    $('#releaseBtn').text('关闭');
                } else {
                    $('#releaseBtn').val('开启');
                    $('#releaseBtn').text('开启');
                }
                notify.success('提示', '发布成功！');
            }).fail(function (data) {
                notify.notifyResp(data);
            });
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                recharge_status: this.rechargeStatus.toJSON(),
                searched: utils.getSearched('op/recharge')
            }));
            var user_dict = {};
            _.each(this.user_collection.toJSON(), function (k) {
                user_dict[k.id] = k.nickname;
            })
            var that = this;
            $('.modify-item').magnificPopup({
                items: {
                    src: '#editRechargePanel',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                callbacks: {
                    beforeOpen: function () {
                        var data_id = $(this.st.el).closest('tr').data('id'),
                            choosen = that.collection.get(data_id);
                        $('#detailId').text(choosen.get('id'));
                        $('#detailUserId').text(choosen.get('user_id'));
                        $('#detailAdminId').text(user_dict[choosen.get('admin_id')]);
                        $('#detailPayAmount').val(choosen.get('pay_amount'));
                        $('#detailType').text(RECHARGE_TYPE[choosen.get('recharge_type')]);
                        $('#detailCreatedAt').text(choosen.get('created_at'));
                        $('#detailStatus').text(RECHARGE_STATUS[choosen.get('status')]);
                        var detailInfo;
                        var recharger_info = choosen.get('recharger_info');
                        if (choosen.get('recharge_type') == 1) {
                          detailInfo = '支付宝交易流水号: '+recharger_info.alipay_order_id+'<br>姓名: '+recharger_info.name+'<br>uid: '+recharger_info.uid;
                        } else if (choosen.get('recharge_type') == 2) {
                          detailInfo = '姓名: '+recharger_info.name+'<br>银行卡号: '+recharger_info.bank_no+'<br>金额: '+recharger_info.price+'<br>时间: '+recharger_info.time+'<br>备注: '+recharger_info.remark;
                        } else if (choosen.get('recharge_type') == 3) {
                          detailInfo = '昵称: '+recharger_info.nickname+'<br>微信号: '+recharger_info.wechat_no+'<br>金额: '+recharger_info.price+'<br>时间: '+recharger_info.time+'<br>备注: '+recharger_info.remark;
                        } else {
                          detailInfo = '无';
                        }
                        $('#detailRechargerInfo').html(detailInfo);
                        var rechargee_info = choosen.get('rechargee_info');
                        if (choosen.get('recharge_type') == 1) {
                          detailInfo = '支付宝账号: '+rechargee_info.alipay_no+'<br>姓名: '+rechargee_info.name;
                        } else if (choosen.get('recharge_type') == 2) {
                          detailInfo = '姓名: '+rechargee_info.name+'<br>银行卡号: '+rechargee_info.bank_no;
                        } else if (choosen.get('recharge_type') == 3) {
                          detailInfo = '微信号: '+rechargee_info.wechat_no;
                        } else {
                          detailInfo = '无';
                        }
                        $('#detailRechargeeInfo').html(detailInfo);
                        if (choosen.get('status') == 2) {
                          $('#submitRecharge').hide();
                          $('#revertRecharge').hide();
                        } else {
                          $('#submitRecharge').show();
                        }
                        if (choosen.get('status') == 4) {
                          $('#revertRecharge').hide();
                        } else if (choosen.get('status') != 2) {
                          $('#revertRecharge').show();
                        }
                        $('#submitRecharge').off('click').click(function() {
                          var pay_amount = $('#detailPayAmount').val();
                          $.post('/admin/recharge/apply/'+data_id+'/'+pay_amount+'/').done(function (resp) {
                              var data = resp.data;
                              $('#submitRecharge').hide();
                              $('#revertRecharge').hide();
                              $('#detailStatus').text(RECHARGE_STATUS[2]);
                              notify.success('提示', '更新成功！');
                          }).fail(function (data) {
                              notify.notifyResp(data);
                          });
                        });
                        $('#revertRecharge').off('click').click(function() {
                          $.post('/admin/recharge/revert/'+data_id+'/').done(function (resp) {
                              var data = resp.data;
                              $('#submitRecharge').hide();
                              $('#revertRecharge').hide();
                              $('#detailStatus').text(RECHARGE_STATUS[4]);
                              notify.success('提示', '更新成功！');
                          }).fail(function (data) {
                              notify.notifyResp(data);
                          });
                        });
                        $('#submitClose').off('click').click(function() {
                            that.doSearch();
                            $.magnificPopup.close();
                        });
                    },
                }
            });
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/recharge/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            $('.datetime-input').datetimepicker({
                format: 'YYYY-MM-DD HH:mm:ss',
            });
            $('.date-input').datetimepicker({
                format: 'YYYY-MM-DD',
            });
            utils.getPaginator(that.options, this.collection.total, '#op/recharge/');
            return this;
        },
        load: function () {
            
            var that = this;
            this.user_collection.fetch({
                reset: true,
                data: {'disable_paginate': 1},
                success: function () {
                    that.collection.fetch({
                        reset: true,
                        data: that.options,
                        error: function (c, r, o) {
                            notify.notifyResp(r);
                            $('#content').append('<h4 class="text-muted">无数据</h4>');
                        }
                    });
                    that.rechargeStatus.fetch({
                        reset: true,
                        error: function (c, r, o) {
                            notify.notifyResp(r);
                            $('#content').append('<h4 class="text-muted">无数据</h4>');
                        }
                    });
                },
                error: function (c, r, o) {
                    notify.notifyResp(r);
                }
            });
            
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/Recharge.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            this.options.$size = 300;
            if (!this.options.created_at) this.options.created_at = tz.today();
            var view = new RechargeListView(this.options);
            view.template = this.template;
            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });

    var RechargeDetailView = Backbone.View.extend({
        tagName: "div",
        className: "panel-body pn",
        events: {
            'click #save': 'toSaveOrCreate',
        },
        initialize: function (options) {
            this.model = new models.Recharge();
            if (options.id) {
                this.model.set('id', options.id);
            }
            this.model.bind('change reset', this.renderWithData, this);
            this.wechat_collection = new models.RechargeWechatCollection();
            this.wechat_collection.bind('change remove reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        _getCurrentInputs: function () {
            var data = {
                'user_id': $('#inputUid').val(),
                'recharge_type': $('#inputRechargeType').val(),
                'recharger_info': {
                },
                'rechargee_info': {
                }
            };
            if (data['recharge_type'] == 3) {
                data['recharger_info'] = {
                    'nickname': $('#inputWechatName').val(),
                    'wechat_no': $('#inputWechatNo').val(),
                    'price': $('#inputWechatPrice').val(),
                    'time': $('#inputWechatTime').val(),
                    'remark': $('#inputWechatRemark').val()
                };
                data['rechargee_info'] = {
                    'wechat_no': $('#inputRechargeWechat').val(),
                    'name': '代理充值'
                }
            }
            return data;
        },
        toSaveOrCreate: function (e) {
            e.preventDefault();
            var isAllRight = utils.simpleCheck();
            if (!isAllRight) {
                notify.error('错误', '输入错误，请检验');
                return;
            }
            var attrs = this._getCurrentInputs();
            this.model.save(attrs, {
                patch: true,
                success: function (model, response) {
                    notify.success('提示', '保存成功！');
                    setTimeout(function () {
                        history.back();
                    }, 500);
                },
                error: function (model, response) {
                    notify.notifyResp(response);
                }
            });
            return false;
        },
        renderWithData: function () {
            this.$el.html(this.template({
                info: this.model.toJSON(),
                recharge_wechats: this.wechat_collection.toJSON(),
            }));
            $('.date-box').datetimepicker({
                format: 'YYYY-MM-DD HH:mm:ss'
            });
        },
        load: function () {
            if (this.model.id) {
                this.model.fetch({
                    reset: true
                });
            } else {
                this.wechat_collection.fetch({
                    reset: true,
                    error: function(c, r, o) {
                        notify.notifyResp(r);
                    }
                });
                this.renderWithData();
            }
        }
    });
    exports.Detail = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/RechargeDetail.html",
        initialize: function (id) {
            this.id = id;
        },
        render: function () {
            var view = new RechargeDetailView(this.id);
            view.template = this.template;

            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });

});
